package org.example.rubbish.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.rubbish.entity.VehicleGps;
import org.example.rubbish.mapper.VehicleGpsMapper;
import org.example.rubbish.service.VehicleGpsService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class VehicleGpsServiceImpl extends ServiceImpl<VehicleGpsMapper, VehicleGps> implements VehicleGpsService {

    @Override
    public Integer getActiveVehiclesCount() {
        return baseMapper.selectActiveVehiclesCount();
    }

    @Override
    public List<VehicleGps> getVehicleRealTimeLocations() {
        return baseMapper.selectRealTimeLocations();
    }

    @Override
    public boolean updateVehicleLocation(String plateNumber, Double longitude,
                                         Double latitude, Double speed, Double direction) {
        try {
            VehicleGps vehicleGps = new VehicleGps();
            vehicleGps.setPlateNumber(plateNumber);
            vehicleGps.setLongitude(BigDecimal.valueOf(longitude));
            vehicleGps.setLatitude(BigDecimal.valueOf(latitude));
            vehicleGps.setSpeed(BigDecimal.valueOf(speed));
            vehicleGps.setDirection(BigDecimal.valueOf(direction));
            vehicleGps.setUpdateTime(new Date());

            // 更新或插入
            QueryWrapper<VehicleGps> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("plate_number", plateNumber);
            VehicleGps existing = this.getOne(queryWrapper);

            if (existing != null) {
                vehicleGps.setId(existing.getId());
                return this.updateById(vehicleGps);
            } else {
                return this.save(vehicleGps);
            }
        } catch (Exception e) {
            return false;
        }
    }
}

